package com.choosefine.it.team.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.choosefine.it.base.BaseService;
import com.choosefine.it.base.SendPush;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.dao.ProjectInfoMapper;
import com.choosefine.it.basedata.model.ProjectInfo;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.StringUtils;
import com.choosefine.it.team.dao.TeamPublishFindWorkerInfoMapper;
import com.choosefine.it.team.model.TeamPublishFindWorkerInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service("teamRecruitmentInfoService")
public class TeamPublishFindWorkerInfoService extends BaseService{
	@Autowired
	private TeamPublishFindWorkerInfoMapper teamPublishFindWorkerInfoMapper;
	
	@Autowired
	private ProjectInfoMapper projectmapper;
		
	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	private SendPush sendPush;

	public Long addTeamRecruitmentInfo(TeamPublishFindWorkerInfo teamRecruitmentInfo) throws BusinessException {
		userInfoUserCodeCheck(teamRecruitmentInfo.getUserCode());
		long isNum = 0;
		try {
			teamRecruitmentInfo.setCtime(DateUtils.getNowTime());
			teamRecruitmentInfo.setPublishTime(DateUtils.getNowTime());
			teamRecruitmentInfo.setReleaseNo("TRI"+System.currentTimeMillis());
			if (StringUtils.isNotBlank(teamRecruitmentInfo.getPublisher())) {
				teamRecruitmentInfo.setVerifyStatus(1);
			} else {
				teamRecruitmentInfo.setVerifyStatus(0);
			}
			isNum = teamPublishFindWorkerInfoMapper.insertSelective(teamRecruitmentInfo);
			if(isNum>0){
				ProjectInfo getProjectInfo = projectmapper.selectProjectInfoByName(teamRecruitmentInfo.getProjectName());
				if (getProjectInfo != null){
					teamRecruitmentInfo.setConstructUnit(getProjectInfo.getConstructUnit());
					teamRecruitmentInfo.setConstructionUnit(getProjectInfo.getConstructionUnit());
					teamRecruitmentInfo.setProjectContractor(getProjectInfo.getContractorName());
					teamRecruitmentInfo.setEngineeringStandard(getProjectInfo.getEngineeringStandard());
					teamRecruitmentInfo.setConstructionUnitCode(getProjectInfo.getConstructUnitCode());
					teamRecruitmentInfo.setProjectContractorCode(getProjectInfo.getManagerUserCode());
				}
				mongoTemplate.insert(teamRecruitmentInfo);
			}
		} catch (Exception e) {
			isNum = 0;
			e.printStackTrace();
			throw new BusinessException(ResultCode.SERVERERROR_INTERNAL, ResultCode.MSG_ERROR, e);
		}
		return isNum;
	}
	 
	public Page<TeamPublishFindWorkerInfo> getTeamRecruitmentInfoList(Map<String, Object> params, PageDTO pageDTO)
			throws BusinessException {
		// 分页
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		Page<TeamPublishFindWorkerInfo> list = teamPublishFindWorkerInfoMapper.getTeamRecruitmentInfoListByUserIdAndTeamId(params);
		return list;
	}

	public int updatePublishstatusByID(Map<String, Object> params) {
		int num = teamPublishFindWorkerInfoMapper.updatePublishstatusByID(params);
		if (num > 0){
			Update update = new Update();
			update.set("publishStatus", params.get("publishStatus"));
			update.set("utime", params.get("utime"));
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(params.get("id"))), update, TeamPublishFindWorkerInfo.class);
		}
		return num;
	}

	public int deleteTeamRecruitmentInfo(Map<String, Object> params) {
		int num = teamPublishFindWorkerInfoMapper.updateIsvalidStatus(params);
		if (num > 0){
			Update update = new Update();
			update.set("isValid", 1);
			update.set("utime", params.get("utime"));
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(params.get("id"))), update, TeamPublishFindWorkerInfo.class);
		}
		return num;
	}

	//  
	// public JsonResult queryTeamRecruitmentPageByCondition(Map<String, Object>
	// params,PageDTO pageDTO) {
	//
	// JsonResult result = new JsonResult();
	// params.putAll(MapUtil.transBean2Map(pageDTO));
	// //分页
	// PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
	// //根据条件查询 数据集
	// Page<TeamRecruitmentInfo> page =
	// teamPublishFindWorkerInfoMapper.queryTeamRecruitmentPageByCondition(params);
	//// result.setPage(page.toPageInfo());
	//
	// return result;
	// }

	/**
	 * 根据 地区、工种、及发布的时间 、推荐、工价 查询各班组发布的招工人数据集
	 */
	 
	public Page<TeamPublishFindWorkerInfo> queryTeamRecruitmentPageByCondition(Map<String, Object> params, Integer pageNo,
			Integer pageSize) {
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		Page<TeamPublishFindWorkerInfo> page = teamPublishFindWorkerInfoMapper.queryTeamRecruitmentPageByCondition(params);
		return page;
	}
	 
	public TeamPublishFindWorkerInfo singleRecruitmentInfoById(Integer id) throws BusinessException {
		if (null == id || id.intValue() == 0) {
			throw new BusinessException(ResultCode.FAILED, CommonConstant.TEAM_RECRUITMENT_ID_IS_NULL);
		}
		return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), TeamPublishFindWorkerInfo.class);
	}
	 
	public int updateTeamRecruitmentInfoByID(TeamPublishFindWorkerInfo info) {
		info.setUtime(DateUtils.getNowTime());
		info.setPublishTime(System.currentTimeMillis());
		info.setIsInsert(CommonConstant.ISINSERT);
		info.setIsValid(CommonConstant.VALID);
		info.setPublisher(null);
		//未通过修改后，加入到待审核列表中（0为待审核） ——update by juchengyang
		info.setVerifyStatus(0);
		int num = teamPublishFindWorkerInfoMapper.updateByPrimaryKeySelective(info);
		if(num > 0){
			Update update = updateModel(info);
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(info.getId())),update , TeamPublishFindWorkerInfo.class);
		}
		return num;
	}

	private Update updateModel(TeamPublishFindWorkerInfo info) {
		Update update = new Update();
		if (info.getProjectAddress() != null) {
			update.set("projectAddress", info.getProjectAddress());
		}
		if(info.getAffcompanyName() != null){
			update.set("affcompanyName", info.getAffcompanyName());
		}
		if(info.getAffcompanyCode() != null){
			update.set("affcompanyCode", info.getAffcompanyCode());
		}
//		if(info.getAffCompanyUserCode() != null){
//			update.set("affCompanyUserCode", info.getAffCompanyUserCode());
//		}
		if(info.getProvinceCode() != null){
			update.set("provinceCode", info.getProvinceCode());
		}
		if(info.getProvinceName() != null){
			update.set("provinceName", info.getProvinceName());
		}
		if(info.getCityCode() != null){
			update.set("cityCode", info.getCityCode());
		}
		if(info.getProvinceName() != null){
			update.set("cityName", info.getProvinceName());
		}
		if(info.getConstructionUnit() != null){
			update.set("constructionUnit", info.getConstructionUnit());
		}
		if(info.getConstructUnit() != null){
			update.set("constructUnit", info.getConstructUnit());
		}
		if(info.getContacts() != null){
			update.set("contacts", info.getContacts());
		}
		if(info.getDescribe() != null){
			update.set("describe", info.getDescribe());
		}
//		if(info.getIsInsert() != 0){
//			update.set("isInsert", info.getIsInsert());
//		}
		if(info.getIsValid() != null){
			update.set("isValid", info.getIsValid());
		}
		if(info.getNeedNum() != null){
			update.set("needNum", info.getNeedNum());
		}
		if(info.getPhone() != null){
			update.set("phone", info.getPhone());
		}
		if(info.getPhone1() != null){
			update.set("phone1", info.getPhone1());
		}
		if(info.getProjectContractor() != null){
			update.set("projectContractor", info.getProjectContractor());
		}
		if(info.getProjectName() != null){
			update.set("projectName", info.getProjectName());
		}
		if(info.getProjectStage() != null){
			update.set("projectStage", info.getProjectStage());
		}
		if(info.getProjectStart() != null){
			update.set("projectStart", info.getProjectStart());
		}
		if(info.getProjectTypeId() != null){
			update.set("projectTypeId", info.getProjectTypeId());
		}
		if(info.getProjectTypeName() != null){
			update.set("projectTypeName", info.getProjectTypeName());
		}
//		if(info.getProjectUserCode() != null){
//			update.set("projectUserCode", info.getProjectUserCode());
//		}
//		if(info.getPublishStatus() != null){
//			update.set("publishStatus", info.getPublishStatus());
//		}
		if(info.getPublishTime() != null){
			update.set("publishTime", info.getPublishTime());
		}
		if(info.getRequirementContent() != null){
			update.set("requirementContent", info.getRequirementContent());
		}
		if(info.getTeamTypeId() != null){
			update.set("teamTypeId", info.getTeamTypeId());
		}
		if(info.getTeamTypeName() != null){
			update.set("teamTypeName", info.getTeamTypeName());
		}
		if(info.getWages() != null){
			update.set("wages", info.getWages());
		}
		if(info.getSettleType() != null){
			update.set("settleType", info.getSettleType());
		}
		if(info.getWorkTypeId() != null){
			update.set("workTypeId", info.getWorkTypeId());
		}
		if(info.getWorkTypeName() != null){
			update.set("workTypeName", info.getWorkTypeName());
		}
		if (null != info.getEngineeringStandard()){
			update.set("engineeringStandard", info.getEngineeringStandard());
		}
		update.set("utime", info.getUtime());
		update.set("verifyStatus", info.getVerifyStatus());
		update.set("reason", null);
		update.set("publisher", null);
		return update;
	}
	 
	public TeamPublishFindWorkerInfo selectTeamRecruitmentInfoDetail(Integer id) {
		return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), TeamPublishFindWorkerInfo.class);
		
	}
	 
	public Page<TeamPublishFindWorkerInfo> selectRecruitmentInfoByCondition(Map<String, Object> params, PageDTO page) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		Page<TeamPublishFindWorkerInfo> list = teamPublishFindWorkerInfoMapper.selectRecruitmentInfoByCondition(params);
		for (int i = 0; i < list.size(); i++) {
			list.set(i, mongoTemplate.findOne(new Query(Criteria.where("_id").is(list.get(i).getId())), TeamPublishFindWorkerInfo.class));
		}
		return list;
	}

	public int updateRecruitmentVerifyStatus(Map<String, Object> params) {
		int num =0;
		num=teamPublishFindWorkerInfoMapper.updateRecruitmentVerifyStatus(params);
//		if(num>0){
//			//对用户进行推送审核结果的通知
//			ArrayList<Integer> idss=(ArrayList<Integer>) params.get("ids");
//			Integer verifyStatus= (Integer) params.get("verifyStatus");
//			for(Integer id:idss){
//				TeamRecruitmentInfo teamRecruitmentInfo = teamPublishFindWorkerInfoMapper.selectByPrimaryKey(id);
//			if(teamRecruitmentInfo!=null){
//				String userCode = teamRecruitmentInfo.getUserCode();
//				Assert.assertNotNull(userCode, "用户编号为空");
//				if(verifyStatus==1){
//					sendPush.sendPushByUsername(userCode, ConstantDef.MSG_TYPE_PUBLISH_ISVERIFY, ConstantDef.MSG_PUSH_PUBLISH_ISVERIFY);
//				}else{
//					sendPush.sendPushByUsername(userCode, ConstantDef.MSG_TYPE_PUBLISH_ISNOT_VERIFY, ConstantDef.MSG_PUSH_PUBLISH_ISNOT_VERIFY);
//				}
//			}
//			}
//		}
		if(num > 0){
			Update update = new Update();
			if (params.get("verifyStatus") != null) {
				update.set("verifyStatus", params.get("verifyStatus"));
			}
			if(params.get("reason") != null){
				update.set("reason", params.get("reason"));
			}
			update.set("publisher", params.get("publisher"));
			update.set("utime", params.get("utime"));
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(params.get("id"))),update , TeamPublishFindWorkerInfo.class);
			
		}
		return num;
	}
	 
	public List<TeamPublishFindWorkerInfo> select(Map<String, Object> params, PageDTO pageDTO) {
		return teamPublishFindWorkerInfoMapper.select(params);
	}

	public int deleteTeamRecruitment(Map<String, Object> params) {
		int num = teamPublishFindWorkerInfoMapper.deleteTeamRecruitment(params);
		if (num > 0){
			List<Integer> ids = (List<Integer>) params.get("ids");
			for (Integer id : ids){
				Update update = new Update();
				update.set("isValid", 1);
				mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, TeamPublishFindWorkerInfo.class);
			}
		}
		return num;
	}



}
